﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Aquaculture;
using Traceable.App.DTOS;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Aquaculture
{
    public class GetAquacultureHandler : IRequestHandler<GetAquacultureCommand, ApiResult<AquacultureDto>>
    {
        private readonly IBaseRepository<Aquaculture_Table> _aquacultureRepo;
        private readonly IBaseRepository<Traceable_Table> _traceableRepositry;
        private readonly IMapper _mapper;

        public GetAquacultureHandler(IBaseRepository<Aquaculture_Table> aquacultureRepo, IMapper mapper, IBaseRepository<Traceable_Table> traceableRepositry)
        {
            _aquacultureRepo = aquacultureRepo;
            _mapper = mapper;
            _traceableRepositry = traceableRepositry;
        }
        /// <summary>
        /// 获取养殖信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<AquacultureDto>> Handle(GetAquacultureCommand request, CancellationToken cancellationToken)
        {
            ApiResult<AquacultureDto> result = new ApiResult<AquacultureDto>();

            var aquaculture = _aquacultureRepo.GetAll().Where(p => p.Batch_Id == request.Batch_Id && !p.IsDelete).FirstOrDefault();
            if(aquaculture!=null)
            {
                result.Code = StatusEnum.OK;
                result.Data = _mapper.Map<AquacultureDto>(aquaculture);
                result.Message = "获取成功";

                var goods = _traceableRepositry.GetAll().Where(p => p.Batch == request.Batch_Id).FirstOrDefault();
                if (goods.Perfect <= 70)
                {
                    goods.Perfect += 30;
                }
                var res = _traceableRepositry.Update(goods);
                
            }
            return Task.FromResult(result);
        }
    }
}
